package com.efounder.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.core.xml.StubObject;
import com.efounder.frame.activity.CommonTransformFragmentActivity;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.frame.fragment.ErrorFragment;
import com.efounder.frame.utils.EFFrameUtils;
import com.efounder.mobilemanager.R;
import com.efounder.service.Registry;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.LogUtils;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

/**
 * fragment加载管理
 */
public class AbFragmentManager {
    private final String TAG = "FragmentManager";
    private Context mContext;
    private BaseFragment frag = null;

    public AbFragmentManager(Context context) {
        mContext = context;
    }

    /**
     * 跳转一个新页面（fragment  activity 都可以）
     *
     * @param mainMenuItem
     * @param inTransition
     * @param outTransition
     * @param forResult
     * @return
     * @throws ClassNotFoundException
     */
    private Class<?> startActivity(StubObject mainMenuItem, int inTransition, int outTransition, boolean forResult) throws ClassNotFoundException {
        Hashtable menuTable = mainMenuItem.getStubTable();
        String className = (String) menuTable.get("AndroidShow");
        if (className == null) {
            //得到类名称（包含路径）
            className = getFragment(mainMenuItem).getClass().getName();
        }
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        Class<?> clazz = loader.loadClass(className.toString());
        //有些是activity的子类但是不是以activity结尾,所以增加isAssignableFrom进行判断
        if (className.toString().endsWith("Activity") || Activity.class.isAssignableFrom(clazz)) {
            Bundle bundle = new Bundle();
            bundle.putSerializable("stubObject", mainMenuItem);
            EFFrameUtils.startActivity((Class<? extends Activity>) clazz, bundle, inTransition, outTransition, forResult);
        } else {
            Bundle bundle = new Bundle();
            bundle.putSerializable("stubObject", mainMenuItem);
            EFFrameUtils.startActivity(CommonTransformFragmentActivity.class, bundle, inTransition, outTransition, forResult);
        }

        return clazz;
    }

    /**
     * 跳转一个新页面（fragment  activity 都可以）
     *
     * @param mainMenuItem
     * @param inTransition
     * @param outTransition
     * @return
     * @throws ClassNotFoundException
     */
    public Class<?> startActivity(StubObject mainMenuItem, int inTransition, int outTransition) throws ClassNotFoundException {
        return startActivity(mainMenuItem, inTransition, outTransition, false);
    }

    public Class<?> startActivityForResult(StubObject mainMenuItem, int inTransition, int outTransition) throws ClassNotFoundException {
        return startActivity(mainMenuItem, inTransition, outTransition, true);
    }

    public Class<?> getActivity(StubObject mainMenuItem, int inTransition, int outTransition) throws ClassNotFoundException {
        Hashtable menuTable = mainMenuItem.getStubTable();
        Object className = menuTable.get("AndroidShow");
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        Class<?> clazz = null;
        if (!className.toString().endsWith("Activity")) {
            clazz = loader.loadClass("com.efounder.frame.activity.CommonTransformFragmentActivity");
        } else {
            clazz = loader.loadClass(className.toString());
        }

        return clazz;
    }

    /**
     * 获取一个fragment
     *
     * @param mainMenuItem
     * @return
     */
    public BaseFragment getFragment(StubObject mainMenuItem) {
        String title = mainMenuItem.getObject("caption", "").toString();
        List<StubObject> subMenus = Registry.getRegEntryList((String) mainMenuItem.getID());
        Hashtable menuTable = mainMenuItem.getStubTable();

        Object viewType = menuTable.get("viewType");
        Object id = menuTable.get("id");

        if (viewType == null) {
            if (subMenus == null || subMenus.size() == 0) {
                frag = getNullContructBaseFragment("com.efounder.fragment.FragmentFirst");

            } else if (subMenus.size() >= 1) {

                //遍历判断显示哪一个fragment
                String currentShowId = mainMenuItem.getString("currentShowId", "");
                for (int i = 0; i < subMenus.size(); i++) {
                    if (currentShowId.equals(subMenus.get(i).getID())) {
                        subMenus.get(i).setString("currentShow", "1");
                    } else {
                        subMenus.get(i).setString("currentShow", "0");
                    }
                }
                Object style = menuTable.get("style");
                if (style != null && "qqstyle".equals(style.toString())) {
                    //上方标题栏qq样式
                    frag = getStubListContructBaseFragment("com.efounder.fragment.PagerSlidingTabQQFragment", subMenus);

                } else if (style != null && ("MagicIndicatorStyle".equals(style.toString())
                        || "slideTab2".equals(style.toString()))) {
                    //左右滑动新样式
                    frag = getStubListContructBaseFragment("com.efounder.fragment.PagerSlidingTab2Fragment", subMenus);

                } else if (style != null && "slideTabOld".equals(style.toString())) {
                    //左右滑动旧的，已经弃用
                    frag = getStubListContructBaseFragment("com.efounder.fragment.PagerSlidingTabFragment", subMenus);

                } else {
                    //最旧的 跟tab2差不多
                    frag = getStubListContructBaseFragment("com.efounder.fragment.PagerSlidingTabFragment", subMenus);

                }
                if (frag == null) {
                    frag = getNullContructBaseFragment("com.efounder.fragment.FragmentFirst");
                    if (frag == null) {
                        frag = new ErrorFragment();
                    }
                }
            }

            /*判断 右上角图标的属性*/
            Object menuType = menuTable.get("menuType");
            if (menuType == null) {
                frag.setRightButtonType("");
            } else if ("weather".equals(menuType)) {

            } else if ("share".equals(menuType)) {
                frag.setRightButtonType("share");
            } else if ("add".equals(menuType)) {//加号按钮
                frag.setRightButtonType("add");
            } else if ("import".equals(menuType)) {//import按钮
                frag.setRightButtonType("import");
            } else if ("star_asset_wallet_change".equals(menuType)) {//星际资产的新建、导入、变更钱包
                frag.setRightButtonType("star_asset_wallet_change");
            } else {
                //可以配置右上角的图标
                frag.setRightButtonType((String) menuType);
                frag.setRightTopButtonICon(mainMenuItem.getString("rithTopIcon", ""));
            }

            return frag;
        }

        if ("slidingTab".equals(String.valueOf(viewType))) {
            frag = getStubListContructBaseFragment("com.efounder.fragment.PagerSlidingTabFragment", subMenus);
        } else if ("home".equals(String.valueOf(viewType))) {
            // frag = new MainFragment(subMenus, title);
            frag = getStubContructBaseFragment("com.efounder.fragment.MainFragment");
            Bundle bundle = new Bundle();
            bundle.putSerializable("stubObject", mainMenuItem);
            frag.setArguments(bundle);
        } else if ("gkhome".equals(String.valueOf(viewType))) {//国堪首页
            // frag = new MainFragment(subMenus, title);
            frag = getStubsTitleHashTableContructBaseFragment("com.efounder.guokan.fragment.GKMainFragment", subMenus, title, menuTable);
        } else if ("webBrowser".equals(String.valueOf(viewType))) {
            frag = getStubTitleContructBaseFragment("com.efounder.fragment.SimpleWebFragmentForForms", mainMenuItem, title);

        } else if ("GWTFormPlay".equals(String.valueOf(viewType))) {
            frag = getStubTitleContructBaseFragment("com.efounder.fragment.WebFragmentForGwtForms", mainMenuItem, title);
        } else if ("webBrowserHtml".equals(String.valueOf(viewType))) {
            frag = getStubTitleContructBaseFragment("com.efounder.fragment.WebviewFragment", mainMenuItem, title);

        } else if ("webView".equals(String.valueOf(viewType))) {
            frag = getStubTitleContructBaseFragment("com.efounder.fragment.SimpleWebFragmentNoRefreshNoForms", mainMenuItem, title);
        } else if ("meeting".equals(String.valueOf(viewType))) {
            frag = getStubTitleContructBaseFragment("com.efounder.zhongyuan.fragment.MeetingWithNightFragment", mainMenuItem, title);
        } else if ("flowTask".equals(String.valueOf(viewType))) {
            //frag = getNullContructBaseFragment("com.efounder.agency.activity.AgentFgNew");
//            frag = getStubContructBaseFragment("com.efounder.agency.activity.AgentFgNew", mainMenuItem);
            //共享 修改为跳转到任务工程，
            frag = getStubContructBaseFragment(ResStringUtil.getString(R.string.task_type_list), mainMenuItem);

        } else if ("mybill".equals(String.valueOf(viewType))) {
//            frag = getNullContructBaseFragment("com.efounder.agency.activity.AgentMyBill");
            //共享 修改为跳转到任务工程，
            frag = getNullContructBaseFragment(ResStringUtil.getString(R.string.task_my_bill));
        } else if ("agentTask".equals(String.valueOf(viewType))) {
            //普光OA 合同费用报销的任务
            frag = getTitleObjectContructBaseFragment("com.efounder.zhongyuan.agency.activity.TaskTypeListWithhrFragment", title, id);
        } else if ("taskCenter".equals(String.valueOf(viewType))) {
            //流程信息（会议申请，风险管控的任务中心）
            frag = getStubTitleContructBaseFragment("com.efounder.zhongyuan.agency.activity.MeetingAgency", mainMenuItem, title);

        } else if ("option".equals(String.valueOf(viewType))) {

            try {
                ClassLoader loader = Thread.currentThread().getContextClassLoader();
                Class<?> clazz = loader.loadClass("com.efounder.fragment.SimpleSettingFragment");

                Method m = clazz.getDeclaredMethod("newInstance", new Class[]{StubObject.class, String.class});
                frag = (BaseFragment) m.invoke(clazz.newInstance(), mainMenuItem, title);

            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }

//            frag = getStubTitleContructBaseFragment("com.efounder.fragment.SimpleSettingFragment", mainMenuItem, title);

        } else if ("message".equals(String.valueOf(viewType))) {
            // frag = new ChatListFragment();
            frag = getNullContructBaseFragment("com.efounder.chat.fragment.ChatListSwipeMenuFragment");

        } else if ("telephone".equals(String.valueOf(viewType))) {
            frag = getNullContructBaseFragment("com.efounder.chat.fragment.TelephoneRecordFragment");

        } else if ("txl".equals(String.valueOf(viewType))) {
            frag = getNullContructBaseFragment("com.efounder.chat.fragment.ContactsFragment");


        } else if ("gzh".equals(String.valueOf(viewType))) {
            frag = getNullContructBaseFragment("com.efounder.chat.fragment.PublicNumberListFragment");
            Bundle bundle = new Bundle();
            bundle.putString("title", title);
            frag.setArguments(bundle);

        } else if ("fwh".equals(String.valueOf(viewType))) {
            frag = getNullContructBaseFragment("com.efounder.chat.fragment.ServiceNumberListFragment");


        } else if ("zzjg".equals(String.valueOf(viewType))) {
            frag = getNullContructBaseFragment("com.efounder.chat.fragment.OrganizationFragment");


        } else if ("find".equals(String.valueOf(viewType))) {
            frag = getNullContructBaseFragment("com.efounder.chat.fragment.FindFragment");


        } else if ("mail".equals(String.valueOf(viewType))) {
            frag = getNullContructBaseFragment("com.efounder.zhongyuan.fragment.EmailMainFragment");

        } else if ("sdjiaoyu".equals(String.valueOf(viewType))) {
            frag = getNullContructBaseFragment("com.efounder.mobilevideo.fragment.EducationFragment");

        } else if ("sdkeji".equals(String.valueOf(viewType))) {
            frag = getNullContructBaseFragment("com.efounder.mobilevideo.fragment.TechFragment");

        } else if ("sdjiankang".equals(String.valueOf(viewType))) {
            frag = getNullContructBaseFragment("com.efounder.mobilevideo.fragment.HealthyFragment");

        } else if ("sdyiliao".equals(String.valueOf(viewType))) {
            frag = getNullContructBaseFragment("com.efounder.mobilevideo.fragment.MedicalFragment");

        }
        //otherdisplay 使用反射的方式加载fragment，用于集成别的项目
        else if ("otherdisplay".equals(String.valueOf(viewType)) || "display".equals(String.valueOf(viewType))) {
            //frag.setAlone这个参数设置为false，给第三方应用使用的时候就不显示我们的标题栏了
            String showClassName = (String) menuTable.get("show");
            if (TextUtils.isEmpty(showClassName)) {
                showClassName = (String) menuTable.get("AndroidShow");
            }
            if (TextUtils.isEmpty(showClassName)) {
                LogUtils.e("未配置 AndroidShow！！！！");
            }
            frag = getStubContructBaseFragment(showClassName, mainMenuItem);
            if (frag == null) {
                frag = getNullContructBaseFragment("com.efounder.fragment.FragmentFirst");
                if (frag == null) {
                    frag = new ErrorFragment();
                }
            }
            Bundle bundle = new Bundle();
            Map<String, String> map = AbfragmentDataUtil.getParamAndValue(menuTable);
            for (String key : map.keySet()) {
                Log.i(TAG, "key=" + key + ":value=" + map.get(key));
                bundle.putString(key, map.get(key));
            }
            // frag.setArguments(bundle);
            if (frag != null) {
                frag.setAlone(false);
            }
        } else if ("openAPP".equals(String.valueOf(viewType))) {
            //frag = new SimpleWebFragment(mainMenuItem,title);
            String packagename = (String) menuTable.get("packagename");
            if (packagename != null) {
                Intent intent = mContext.getPackageManager().getLaunchIntentForPackage("com.example.liuxiang");
                if (intent != null) {
                    // 这里跟Activity传递参数一样的嘛，不要担心怎么传递参数，还有接收参数也是跟Activity和Activity传参数一样
                    //intent.putExtra("name", "Liu xiang");
                    //intent.putExtra("birthday", "1983-7-13");
                    mContext.startActivity(intent);
                } else {
                    // 没有安装要跳转的app应用，提醒一下
                    // Toast.makeText(mContext.getApplicationContext(), "哟，赶紧下载安装这个APP吧", Toast.LENGTH_LONG).show();
                    frag = getStubTitleContructBaseFragment("com.efounder.fragment.SimpleWebFragmentNoRefreshNoForms", mainMenuItem, title);
                }
            } else {
                frag = getStubTitleContructBaseFragment("com.efounder.fragment.SimpleWebFragmentNoRefreshNoForms", mainMenuItem, title);
            }
        } else if ("menuMore".equals(String.valueOf(viewType))) {
            frag = getNullContructBaseFragment("com.efounder.fragment.MenuFragment");

        } else if ("video".equals(String.valueOf(viewType))) {
            frag = getStubTitleContructBaseFragment("com.efounder.fragment.VedioDetailFrag", mainMenuItem, title);
        } else if ("notice".equals(String.valueOf(viewType))) {

            frag = getStubTitleContructBaseFragment("com.efounder.zhongyuan.fragment.NoticeFragmentBack", mainMenuItem, title);

        } else if ("FullScreenWebView".equals(String.valueOf(viewType))) {
            frag = getStubTitleContructBaseFragment("com.efounder.fragment.SimpleWebFragmentNoRefreshNoForms", mainMenuItem, title);

        } else if ("welcome".equals(String.valueOf(viewType))) {
            frag = getNullContructBaseFragment("com.efounder.fragment.WelcomeGuideFragment");

        } else if ("taskflow".equals(String.valueOf(viewType))) {
            frag = getNullContructBaseFragment("com.pizidea.imagepicker.ui.WorkOrderPeopleDetailFragment");

        } else if ("YJWX".equals(String.valueOf(viewType))) {
            //硬件维修系统信息2018/01/15 yqs
            frag = getStubTitleContructBaseFragment("com.efounder.zhongyuan.agency.activity.YjwxSystemFragment", mainMenuItem, title);

        } else {
            frag = getNullContructBaseFragment("com.efounder.fragment.FragmentFirst");
        }
        if (frag == null) {
            frag = getNullContructBaseFragment("com.efounder.fragment.FragmentFirst");
        }
        /*判断 右上角图标的属性*/
        Object menuType = menuTable.get("menuType");
        if (menuType == null) {
            frag.setRightButtonType("");
        } else if ("weather".equals(menuType)) {
            frag.setRightButtonType("weather");

        } else if ("share".equals(menuType)) {
            frag.setRightButtonType("share");
        } else if ("import".equals(menuType)) {
            frag.setRightButtonType("import");
        }

        //fixme 统一设置 Arguments
        if (frag != null && frag.getArguments() == null) {
            Bundle bundle = new Bundle();
            bundle.putSerializable("stubObject", mainMenuItem);
            frag.setArguments(bundle);
        }

        return frag;
    }


    /**
     * 获取无参构造器的fragment
     *
     * @param className
     * @return
     */
    private BaseFragment getNullContructBaseFragment(String className) {
        try {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            Class<?> clazz = loader.loadClass(className);
            //获取无参构造器
            Constructor<?> cons = clazz.getDeclaredConstructor();
            //实例化
            frag = (BaseFragment) cons.newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return frag;
    }

    private BaseFragment getStubListContructBaseFragment(String className, List<StubObject> stubObjects) {
        try {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            Class<?> clazz = loader.loadClass(className);
            //获取有参构造器，根据参数类型。
            Constructor<?> cons1 = clazz.getDeclaredConstructor(List.class);
            //实例化
            frag = (BaseFragment) cons1.newInstance(stubObjects);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return frag;
    }

    private BaseFragment getStubTitleContructBaseFragment(String className, StubObject stubObject, String title) {
        try {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            Class<?> clazz = loader.loadClass(className);
            //获取无参构造器
            //Constructor<?> cons = clazz.getDeclaredConstructor();
            //获取有参构造器，根据参数类型。
            Constructor<?> cons1 = clazz.getDeclaredConstructor(StubObject.class, String.class);
            //实例化
            frag = (BaseFragment) cons1.newInstance(stubObject, title);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return frag;
    }

    private BaseFragment getStubContructBaseFragment(String className) {
        try {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            Class<?> clazz = loader.loadClass(className);

            //实例化
            frag = (BaseFragment) clazz.newInstance();

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return frag;
    }

    /**
     * 获取 stubObject构造方法的fragment
     *
     * @param className
     * @param stubObject
     * @return
     */
    private BaseFragment getStubContructBaseFragment(String className, StubObject stubObject) {
        try {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            Class<?> clazz = loader.loadClass(className);
            try {
                Constructor<?> cons1 = clazz.getDeclaredConstructor(StubObject.class);
                //实例化
                frag = (BaseFragment) cons1.newInstance(stubObject);
                LogUtils.e("警告：请检查" + className + "中是否具有无参构造方法，在特定情况下会引起应用闪退，请使用getArguments获取参数信息，如果含有无参构造方法，" +
                        "请改造后去除stubObject构造方法");
            } catch (NoSuchMethodException e) {
                frag = (BaseFragment) clazz.newInstance();
                Bundle bundle = new Bundle();
                bundle.putSerializable("stubObject", stubObject);
                frag.setArguments(bundle);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return frag;
    }

    private BaseFragment getStubsTitleHashTableContructBaseFragment(String className, List stubObjects, String title, Hashtable hashtable) {
        try {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            Class<?> clazz = loader.loadClass(className);
            //获取无参构造器
            //Constructor<?> cons = clazz.getDeclaredConstructor();
            //获取有参构造器，根据参数类型。
            Constructor<?> cons1 = clazz.getDeclaredConstructor(List.class, String.class, Hashtable.class);
            //实例化
            frag = (BaseFragment) cons1.newInstance(stubObjects, title, hashtable);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return frag;
    }

    private BaseFragment getTitleObjectContructBaseFragment(String className, String title, Object object) {
        try {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            Class<?> clazz = loader.loadClass(className);
            //获取无参构造器
            //Constructor<?> cons = clazz.getDeclaredConstructor();
            //获取有参构造器，根据参数类型。
            Constructor<?> cons1 = clazz.getDeclaredConstructor(String.class, Object.class);
            //实例化
            frag = (BaseFragment) cons1.newInstance(title, object);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return frag;
    }

    private BaseFragment getTitleObjectContructBaseFragment(String className, String title) {
        try {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            Class<?> clazz = loader.loadClass(className);
            //获取无参构造器
            //Constructor<?> cons = clazz.getDeclaredConstructor();
            //获取有参构造器，根据参数类型。
            Constructor<?> cons1 = clazz.getDeclaredConstructor(String.class, Object.class);
            //实例化
            frag = (BaseFragment) cons1.newInstance(title);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return frag;
    }
}
